package com.annhoa.interfaces.facade;

import com.annhoa.domain.entity.SysUser;
import com.annhoa.infrastructure.common.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.annhoa.domain.service.AuthService;

import javax.servlet.http.HttpServletRequest;

/**
 * @author annhoa ajax 登录
 */
@Api(value = "鉴权登陆模块", tags = "鉴权登陆模块")
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    /**
     * POST登录
     *
     * @param username
     * @param password
     * @return
     * @throws AuthenticationException
     */
    @ApiOperation(value = "用户名密码登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @PostMapping(value = "/login")
    public AjaxResult createAuthenticationToken(
            String username, String password) throws AuthenticationException {
        return AjaxResult.success(authService.login(username, password));
    }

    /**
     * get登录
     *
     * @param request
     * @return
     * @throws AuthenticationException
     */
    @GetMapping(value = "/refresh")
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request)
            throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        if (StringUtil.isEmpty(token)) {
            return ResponseEntity.badRequest().body(null);
        }
        return ResponseEntity.ok(authService.refresh(token));
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody SysUser addedSysUser) {
        return ResponseEntity.ok(authService.register(addedSysUser));
    }
}
